<template>
  <Modal
    width="800"
    v-model="visiable"
    :closable="false"
    :mask-closable="false"
    :title="modalTitle"
  >
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80" style="width: 700px">
      <Row>
        <Col :span="span">
          <FormItem label="账号" prop="account">
            <Input v-model="formValidate.account" />
          </FormItem>
        </Col>
        <Col :span="span">
          <FormItem label="姓名" prop="userName">
            <Input v-model="formValidate.userName" />
          </FormItem>
        </Col>
        <Col :span="span" v-if="!isEdit">
          <FormItem label="密码" prop="password">
            <Input type="password" v-model="formValidate.password" />
          </FormItem>
        </Col>
        <Col :span="span" v-if="!isEdit">
          <FormItem label="确认密码" prop="confirmPassword">
            <Input type="password" v-model="formValidate.confirmPassword" />
          </FormItem>
        </Col>
        <Col :span="span">
          <FormItem label="部门" prop="pertainCode">
            <Cascader v-model="formValidate.pertainCode" :data="departmentList" change-on-select />
          </FormItem>
        </Col>
        <Col :span="span">
          <FormItem label="角色" prop="roleCodes">
            <Select v-model="formValidate.roleCodes" multiple style="width:270px">
              <Option v-for="item in roleList" :value="item.roleCode" :key="item.value">{{ item.roleName }}</Option>
            </Select>
          </FormItem>
        </Col>
        <Col :span="span">
          <FormItem label="手机号" prop="phone">
            <Input v-model="formValidate.phone" />
          </FormItem>
        </Col>
        <Col :span="span">
          <FormItem label="邮箱" prop="email">
            <Input v-model="formValidate.email" />
          </FormItem>
        </Col>
        <Col :span="span">
          <FormItem label="备注" prop="description">
            <Input v-model="formValidate.description" />
          </FormItem>
        </Col>
      </Row>
    </Form>
    <div slot="footer">
      <Button @click="handleCancel">取消</Button>
      <Button type="primary" @click="handleOk" :loading="isLoading">确定</Button>
    </div>
</Modal>
</template>

<script>
import {
  queryOrgListSelect,
  queryRoleList,
  addUser,
  editUser
} from '@/api/user-manage.js'

export default {
  name: 'AddUserModal',
  props: ['isShowModal', 'modalTitle', 'rowData'],
  data: function () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.formValidate.confirmPassword !== '') {
          // 对第二个密码框单独验证
          this.$refs.formValidate.validateField('confirmPassword')
        }
        callback()
      }
    }
    const validatePassCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请确认密码'))
      } else if (value !== this.formValidate.password) {
        callback(new Error('您输入的输入的两次密码不匹配!'))
      } else {
        callback()
      }
    }
    return {
      span: 12, // 设置col的span
      isLoading: false,
      visiable: this.isShowModal,
      isEdit: false,
      row: this.rowData,
      departmentList: [],
      roleList: [],
      formValidate: {
        account: '',
        userName: '',
        password: '',
        confirmPassword: '',
        pertainCode: [],
        roleCodes: [],
        phone: '',
        email: ''
      },
      ruleValidate: {
        account: [{ required: true, message: '请填写账号', trigger: 'blur' }],
        userName: [{ required: true, message: '请填写姓名', trigger: 'blur' }],
        password: [{ required: true, validator: validatePass, trigger: 'blur' }],
        confirmPassword: [{ required: true, validator: validatePassCheck, trigger: 'blur' }],
        pertainCode: [{ type: 'array', required: true, message: '请填选择部门', trigger: 'change' }],
        roleCodes: [{ type: 'array', required: true, message: '请填选择角色', trigger: 'change' }]
      }
    }
  },
  watch: {
    isShowModal (val) {
      this.visiable = val
    },
    rowData (val) {
      // 编辑回显
      if (val.userCode) {
        this.isEdit = true
        // 修改时，查找父级节点做回显
        const getParentCodes = []
        if (val.deptTree) {
          val.deptTree.map(item => {
            if (item.pcode !== '0') {
              getParentCodes.push(item.pcode)
            }
          })
        }
        getParentCodes.push(val.pertainCode)
        this.formValidate = {
          userCode: val.userCode,
          account: val.account,
          userName: val.userName,
          pertainCode: getParentCodes,
          roleCodes: val.roleInfo.map(item => item.roleCode),
          phone: val.phone,
          email: val.email,
          description: val.description
        }
      } else {
        this.isEdit = false
        this.formValidate = {
          account: '',
          userName: '',
          password: '',
          confirmPassword: '',
          pertainCode: [],
          roleCodes: []
        }
      }
    }
  },
  methods: {
    handleOk () {
      this.$refs['formValidate'].validate((valid) => {
        if (valid) {
          this.isLoading = true
          const values = this.formValidate
          const results = {
            ...values,
            pertainCode: values.pertainCode.splice(-1, 1)[0] // 传部门数组最后一级code
          }
          let messageText = '添加成功'
          let disptch = addUser
          if (this.isEdit) {
            messageText = '修改成功'
            disptch = editUser
          }
          disptch(results).then((response) => {
            const { data } = response
            if (data.code === 2000) {
              this.$Message.success(messageText)
              this.$emit('handleSubmit')
            } else {
              this.$Message.error(data.msg || '系统错误，请稍后再试')
            }
            this.isLoading = false
          })
        }
      })
    },
    handleCancel () {
      this.isLoading = false
      this.$refs['formValidate'].resetFields() // 重置form表单
      this.$emit('closeModal')
    },
    getDepartmentList () {
      queryOrgListSelect().then((response) => {
        const { data } = response
        if (data.code === 2000) {
          this.departmentList = data.data
        } else {
          this.$Message.error(data.msg || '系统错误，请稍后再试')
        }
      })
    },
    getRoleList () {
      queryRoleList().then((response) => {
        const { data } = response
        if (data.code === 2000) {
          this.roleList = data.data
        } else {
          this.$Message.error(data.msg || '系统错误，请稍后再试')
        }
      })
    }
  },
  mounted () {
    this.getDepartmentList()
    this.getRoleList()
  }
}
</script>
